#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <libgen.h>
#include <limits.h>
#include <sched.h>
#include <sys/resource.h>
#include "config.h"
#include "modbus_client.h"
#include "logger.h"


void print_summary_statistics(modbus_client_t clients[4]) {
    uint64_t total_ops = 0;
    uint64_t total_success = 0;
    uint64_t total_timeout = 0;
    uint64_t total_errors = 0;
    
    printf("\n=== Summary Statistics ===\n");
    
    for (int i = 0; i < 4; i++) {
        total_ops += clients[i].total_operations;
        total_success += clients[i].successful_operations;
        total_timeout += clients[i].timeout_errors;
        total_errors += clients[i].other_errors;
        
        printf("Link %d: %lu ops, %.1f%% success\n", 
              i, clients[i].total_operations,
              (double)clients[i].successful_operations / clients[i].total_operations * 100);
    }
    
    printf("\nTotal: %lu operations\n", total_ops);
    printf("Success rate: %.1f%%\n", (double)total_success / total_ops * 100);
    printf("Timeout errors: %lu\n", total_timeout);
    printf("Other errors: %lu\n", total_errors);
}

//之前通过全局变量，需要进行修改
void signal_handler(int sig) {
    printf("\nReceived signal %d, shutting down gracefully...\n", sig);
    // g_client.running = false;
}

void print_config_summary(const config_t* config) {
    printf("\n=== Modbus Pressure Test Configuration ===\n");
    printf("Polling Interval: %d ms\n", config->polling_interval_ms);
    printf("Test Duration: %u hours %u minutes %u seconds\n",
           config->test_duration.duration_hours,
           config->test_duration.duration_minutes,
           config->test_duration.duration_seconds);
    printf("Holding Registers: %d-%d\n", 
           config->holding_register_range.start_address,
           config->holding_register_range.end_address);
    
    printf("\n=== Modbus Servers Configuration ===\n");
    for (int i = 0; i < 4; i++) {
        printf("Server %d: %s:%d (Slave ID: %d)\n", i,
               config->modbus_servers[i].ip,
               config->modbus_servers[i].port,
               config->modbus_servers[i].slave_id);
        printf("  Disable Nagle: %s\n", 
               config->modbus_servers[i].disable_nagle ? "Yes" : "No");
    }
    
    printf("\n=== Real-time Performance Configuration ===\n");
    for (int i = 0; i < 4; i++) {
        printf("Link %d:\n", i);
        printf("  CPU Core: %d\n", config->rt_configs[i].thread_cpu_core);
        printf("  Thread Priority: %d\n", config->rt_configs[i].thread_priority);
        printf("  Memory Locking: %s\n", config->rt_configs[i].lock_memory ? "Enabled" : "Disabled");
        printf("  TCP Send Buffer: %d bytes\n", config->rt_configs[i].tcp_send_buffer_size);
        printf("  TCP Recv Buffer: %d bytes\n", config->rt_configs[i].tcp_recv_buffer_size);
        printf("  TCP Delay ACK: %s\n", config->rt_configs[i].disable_tcp_delay_ack ? "Disabled" : "Enabled");
    }
    printf("==========================================\n\n");
}

int main(int argc, char* argv[]) {
    const char* config_file = "../settings.json";
    
    if (argc > 1) {
        config_file = argv[1];
    }

    // 加载配置
    config_t config;
    if (load_config(config_file, &config) != 0) {
        fprintf(stderr, "Using default configuration\n");
        // 设置合理的默认值...
    }

    print_config_summary(&config);

    modbus_client_t clients[4];
    pthread_t threads[4];

    for(int i=0;i<4;i++){
        memset(&clients[i], 0, sizeof(modbus_client_t));
        clients[i].link_id = i;
        clients[i].config = config;

        if (modbus_client_init(&clients[i], &config, i) != 0) {
            fprintf(stderr, "Failed to initialize Modbus client for link %d\n", i);
            continue;
        }

        // 初始化时间统计
        init_timing_stats(&clients[i].timing_stats);
        
        // 初始化日志
        init_logger(&clients[i]);
        
        // 创建线程属性
        pthread_attr_t attr;
        pthread_attr_init(&attr);
        
        // 设置调度策略为FIFO实时调度
        pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
        struct sched_param param = {
            .sched_priority = config.rt_configs[i].thread_priority
        };
        pthread_attr_setschedparam(&attr, &param);
        pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
        
        // 设置CPU亲和性
        cpu_set_t cpuset;
        CPU_ZERO(&cpuset);
        CPU_SET(config.rt_configs[i].thread_cpu_core, &cpuset);
        pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpuset);

        if(pthread_create(&threads[i],&attr,modbus_client_thread,&clients[i])){
            perror("pthread_create failed");
            modbus_client_cleanup(&clients[i]);
            continue;
        }

        log_message(&clients[i], "Thread started on CPU core %d",config.rt_configs[i].thread_cpu_core);
    }

    for (int i = 0; i < 4; i++)
    {
        if(threads[i]){
            pthread_join(threads[i],NULL);
            close_logger(&clients[i]);

            // 打印最终统计
            printf("\n=== Link %d Final Statistics ===\n", i);
            printf("Total operations: %lu\n", clients[i].total_operations);
            printf("Success rate: %.1f%%\n", 
                  (double)clients[i].successful_operations / clients[i].total_operations * 100);
            print_timing_stats(&clients[i].timing_stats, clients[i].timer.period_ns);
        }
    }
    
    // 汇总统计
    print_summary_statistics(clients);

    return 0;
}
